package com.example.everying.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.context.UserContext;
import com.example.everying.mapper.content.ActivityArticleMapper;
import com.example.everying.mapper.order.TransferRecordMapper;
import com.example.everying.mapper.pay.PaymentOrderMapper;
import com.example.everying.mapper.pay.TransferBatchMapper;
import com.example.everying.mapper.user.UserBalanceTransactionMapper;
import com.example.everying.model.dto.user.UserBalanceTransactionDetailDto;
import com.example.everying.model.dto.user.TransactionPageDto;
import com.example.everying.model.dto.user.UserBalanceTransactionEntityDto;
import com.example.everying.model.dto.user.UserBalanceTransactionStaticDto;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.entity.order.TransferRecord;
import com.example.everying.model.entity.pay.PaymentOrderEntity;
import com.example.everying.model.entity.pay.TransferBatchEntity;
import com.example.everying.model.entity.user.UserBalanceTransactionEntity;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.user.UserBalanceTransactionDetailVo;
import com.example.everying.model.entity.user.UserLabelRelEntity;
import com.example.everying.model.vo.user.TransactionPageResultVo;
import com.example.everying.model.vo.user.UserBalanceTransactionVO;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.content.ActivityArticleService;
import com.example.everying.service.content.impl.ActivityArticleServiceImple;
import com.example.everying.service.pay.PaymentOrderService;
import com.example.everying.service.pay.TransferBatchService;
import com.example.everying.model.vo.user.UserTransactionPageVo;
import com.example.everying.service.user.UserBalanceTransactionService;
import com.example.everying.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BalanceTransactionServiceImpl extends ServiceImpl<UserBalanceTransactionMapper, UserBalanceTransactionEntity> implements UserBalanceTransactionService {

    @Autowired
    private PaymentOrderMapper paymentOrderService;
    @Autowired
    private TransferBatchMapper transferBatchService;
    @Autowired
    private ActivityArticleMapper activityArticleService;
    @Autowired
    private TransferRecordMapper transferRecordService;




    @Autowired
    private UserServiceImpl userService;

    @Override
    public List<UserBalanceTransactionEntity> getTransactionsByUserId(String userId) {
        return query().eq("user_id", userId).list();
    }

    /**
     * @param pageParam
     * @param dto
     * @return
     */
    @Override
    public IPage<UserBalanceTransactionEntity> selectPage(Page<UserBalanceTransactionEntity> pageParam, UserBalanceTransactionEntityDto dto) {
        //创建查询wrapper
        QueryWrapper<UserBalanceTransactionEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (dto.getUserId() != null && !dto.getUserId().isEmpty()) {
            wrapper.eq("user_id", dto.getUserId());
        }
        if (dto.getTxId() != null && !dto.getTxId().isEmpty()) {
            wrapper.eq("tx_id", dto.getTxId());
        }
        if (dto.getTxType() != null && !dto.getTxType().isEmpty()) {
            wrapper.eq("tx_type", dto.getTxType());
        }
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            wrapper.between("create_time", dto.getStartTime(), dto.getEndTime());
        }
        //调用mapper的方法
        return baseMapper.selectPage(pageParam, wrapper);
    }


    @Override
    public boolean updateTransactionStatus(String txId, int status) {
        return update().eq("tx_id", txId).set("tx_status", status).update();
    }

    /**
     * @param dto
     * @return
     */
    @Override
    public UserBalanceTransactionVO stats(Page<UserBalanceTransactionEntity> pageParam, UserBalanceTransactionStaticDto dto) {
        QueryWrapper<UserBalanceTransactionEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        UserEntity user = UserContext.getUser();
        log.info("用户ID：{}", user.getId());
        if (user != null && !user.getId().isEmpty()) {
            wrapper.eq("user_id", user.getId());
        }
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            LocalDateTime startDateTime = dto.getStartTime().atStartOfDay();
            LocalDateTime endDateTime = dto.getEndTime().plusDays(1).atStartOfDay();
            wrapper.between("create_time", startDateTime, endDateTime);
        }
        List<UserBalanceTransactionEntity> list = baseMapper.selectList(wrapper);
        if (dto.getType() != null && !dto.getType().isEmpty()) {
            List<String> txType = getTxTypeList(dto.getType());
            if (dto.getType() != null) {
                wrapper.in("tx_type", txType);
            }
        }


        Page<UserBalanceTransactionEntity> page = baseMapper.selectPage(pageParam, wrapper);
        UserBalanceTransactionVO vo = new UserBalanceTransactionVO();

        vo.setUserInfoVo(user);
        vo.setPage(page);
        list.forEach(item -> {
            addAmt(vo, item);
        });

        return vo;
    }

    @Override
    public Result<?> selectPageWithUser(TransactionPageDto dto) {
        Page<UserBalanceTransactionEntity> page = new Page<>(dto.getPage(), dto.getLimit());
        LambdaQueryWrapper<UserBalanceTransactionEntity> wrapper = new LambdaQueryWrapper<>();
        if (dto.getTxId() != null && !dto.getTxId().isEmpty()){
            wrapper.eq(UserBalanceTransactionEntity::getTxId,  dto.getTxId());
        }
        wrapper.orderByDesc(UserBalanceTransactionEntity::getId);
        IPage<UserBalanceTransactionEntity> list = baseMapper.selectPage(page,  wrapper);
        Set<String> userIds = list.getRecords().stream()
                .map(UserBalanceTransactionEntity::getUserId)
                .collect(Collectors.toSet());
        List<UserEntity> users = userService.getUserByIds(userIds);
        // 4. 创建用户ID到用户名的映射
        Map<String, String> userIdToUsernameMap = users.stream()
                .collect(Collectors.toMap(
                        UserEntity::getId,
                        UserEntity::getUserName,
                        (existing, replacement) -> existing));

        // 5. 转换为 UserTransactionPageVo 列表
        List<UserTransactionPageVo> voList = list.getRecords().stream()
                .map(entity -> {
                    UserTransactionPageVo vo = new UserTransactionPageVo();
                    // 复制父类属性
                    BeanUtils.copyProperties(entity,  vo);
                    // 设置用户名
                    vo.setUserName(userIdToUsernameMap.getOrDefault(entity.getUserId(),  "系统账户"));
                    return vo;
                })
                .collect(Collectors.toList());

        TransactionPageResultVo vo = new TransactionPageResultVo();
        vo.setRecords(voList);
        vo.setTotal((int) list.getTotal());
        vo.setSize((int) page.getSize());
        vo.setCurrent((int) page.getCurrent());
        vo.setPages((int) list.getPages());


        return Result.ok(vo);
    }


    /**
     * @param dto
     * @return
     */
    @Override
    public Result<?> detail(UserBalanceTransactionDetailDto dto) {
        UserBalanceTransactionEntity entity = baseMapper.selectById(dto.getId());
        UserBalanceTransactionDetailVo vo = new UserBalanceTransactionDetailVo();
        vo.setType(entity.getType());
        vo.setCreateTime(entity.getCreateTime());
        vo.setAmount(entity.getChangeAmount());
        vo.setChannel("余额");
        vo.setDescription("无"); // 默认：无
        switch (entity.getType()) {
            case "2":
                QueryWrapper<PaymentOrderEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("transaction_id", entity.getTxId());
                PaymentOrderEntity paymentOrderEntity = paymentOrderService.selectOne(wrapper);
                vo.setDescription("用户充值");
                vo.setTxId(paymentOrderEntity.getTransactionId());
                break;
            case "3":
                QueryWrapper<TransferBatchEntity> transferQueryWrapper = new QueryWrapper<>();
                transferQueryWrapper.eq("batch_no", entity.getTxId());
                TransferBatchEntity transferBatchEntity = transferBatchService.selectOne(transferQueryWrapper);
                vo.setDescription("用户提现");
                vo.setTxId(transferBatchEntity.getChannelBatchNo());
                break;
            case "6":
                QueryWrapper<TransferRecord> transferRecordQueryWrapper = new QueryWrapper<>();
                transferRecordQueryWrapper.eq("tx_no", entity.getTxId());
                transferRecordQueryWrapper.eq("from_user_id", entity.getUserId()).
                        or().
                        eq("to_user_id", entity.getUserId()).
                        eq("tx_no", entity.getTxId());;
                TransferRecord transferRecord = transferRecordService.selectOne(transferRecordQueryWrapper);
                if (transferRecord != null) {
                    vo.setDescription("用户转账");
                    vo.setTxId(transferRecord.getTxNo());
                }
            default:
                ActivityArticle activityArticle = activityArticleService.selectById(entity.getTxId());
                if (activityArticle != null) {
                    vo.setDescription(activityArticle.getTitle());
                }
                break;
        }

        return Result.ok(vo);
    }

    private List<String> getTxTypeList(String type) {
        List<String> txType = new ArrayList<>();
        switch (type) {
            case "1" -> {
                txType.add("0");
                txType.add("3");
            }
            case "0" -> {
                txType.add("1");
                txType.add("2");
            }
            default -> {
                txType.add("0");
                txType.add("1");
                txType.add("2");
                txType.add("3");
            }
        }
        return txType;
    }

    private UserBalanceTransactionVO addAmt(UserBalanceTransactionVO vo, UserBalanceTransactionEntity item) {
        switch (item.getTxType()) {
            case "0":
                vo.setInAmt(vo.getInAmt().add(item.getChangeAmount()));
            case "1":
                vo.setOutAmt(vo.getOutAmt().add(item.getChangeAmount()));
                break;
            case "2":
                vo.setOutAmt(vo.getOutAmt().add(item.getChangeAmount()));
                break;
            case "3":
                vo.setInAmt(vo.getInAmt().add(item.getChangeAmount()));
                break;
            default:
                break;
        }
        return vo;
    }
}
